package fr.gestionimmo.locator;

import java.util.HashMap;
import java.util.Map;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.reflect.ReflectionFactory.GetReflectionFactoryAction;

import fr.gestionimmo.exception.DaoLocatorException;
import fr.gestionimmoejb.dao.UtilisateurDao;
import fr.gestionimmoejb.service.AdministrationManager;
import fr.gestionimmoejb.service.GestionManager;

public class ServiceLocator {
	
	protected final Log log = LogFactory.getLog(getClass());
	
	private InitialContext context = null;
	private static ServiceLocator instance = null;
	
	private Map<String, Object> cache = new HashMap<String, Object>();
	
	private ServiceLocator(){		
		try{			
			context = new InitialContext();
		} catch (NamingException namingException){
			namingException.printStackTrace();
		}		
	}

	public static ServiceLocator getInstance(){
		if (instance==null){
			instance = new ServiceLocator();
		}
		return instance;
	}
	
	/**
	 * 
	 * @param jndiName
	 * @return
	 * @throws DaoLocatorException
	 */
    private synchronized Object getRemoteDao(String jndiName) throws DaoLocatorException{
    	log.debug("getRemoteDao()");
        Object remoteObject = cache.get(jndiName);
        if (remoteObject == null) {
            try {
                remoteObject = context.lookup(jndiName);
                cache.put(jndiName, remoteObject);
            } catch (Exception e) {
            	log.error("getRemoteDao() : " + e.getLocalizedMessage());
                throw new DaoLocatorException(e);
            }
        }
        return remoteObject;
    }

	/**
	 * 
	 * getUserDao()
	 * 
	 * @return
	 * @throws DaoLocatorException
	 */
	public AdministrationManager getAdministrationManager()throws DaoLocatorException {
		return (AdministrationManager)this.getRemoteDao("AmiPlouGestionEAR/AdministrationManagerImpl/local");
	}
	public GestionManager getGestionManager()throws DaoLocatorException {
		return (GestionManager)this.getRemoteDao("AmiPlouGestionEAR/GestionManagerImpl/local");
	}
}
